package com.cpecc.dao.wuzi;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.cpecc.model.system.User;
import com.cpecc.model.wuzi.TuiHuo;

@Repository
public class TuiHuoDao {

	@Resource
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public void save(TuiHuo tuiHuo){
		Session session=sessionFactory.getCurrentSession();
		session.save(tuiHuo);
		session.flush();
	}
	
	public TuiHuo get(String id){
		return (TuiHuo) sessionFactory.getCurrentSession().get(TuiHuo.class, id);
	}
	
	public boolean cover(TuiHuo tuiHuo){
		String hql="update TuiHuo t set t.huanJie=? where t.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, tuiHuo.getHuanJie());
		query.setString(1, tuiHuo.getId());
		return query.executeUpdate()>0;
	}
	
	@SuppressWarnings("unchecked")
	public List<TuiHuo> getAllTuiHuoSQ(int huanJie){
		String hql="from TuiHuo t where t.huanJie.id=? order by t.shenQingRQ desc";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, huanJie);
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<TuiHuo> getAllTuiHuoSQ2CMR(int huanJie, User user){
		String hql="from TuiHuo t where t.huanJie.id=? and t.wuZi.caiMaiR=? order by t.shenQingRQ desc";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, huanJie);
		query.setParameter(1, user);
		return query.list();
	}
	
	public boolean hasWuZi(String wuZiId){
		String hql="from TuiHuo t where t.wuZi.id=? and t.huanJie.id<304";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, wuZiId);
		return query.list().size()>0;
	}
	
	public boolean hasLiuCheng(User user){
		String hql="from TuiHuo t where t.user=? and t.huanJie.id<304";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, user);
		return query.list().size()>0;
	}
	
	@SuppressWarnings("unchecked")
	public List<TuiHuo> activeTuiHuo(){
		String hql="from TuiHuo t where t.huanJie.id<304";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}
}
